package com.zyk.leetcode;

/**
 * @author zhangsan
 * @date 2021/4/4 17:02
 */
public class J18 {


    public static class ListNode {
        int val;
        ListNode next;

        ListNode(int x) {
            val = x;
        }
    }

    /**
     * https://leetcode-cn.com/problems/shan-chu-lian-biao-de-jie-dian-lcof/
     */
    public static ListNode deleteNode(ListNode head, int val) {
        // 直接先从前边删.
        while (head != null) {
            if(! (head.val == val) ) {
                break;
            }
            head = head.next;
        }
        // 此时head可能是个节点, 也可能删完了指向null
        ListNode cur = head;
        ListNode pre = head;
        while (cur != null) {
            if(cur.val == val) {
                pre.next = cur.next;
            }else {
                pre = cur;
            }
            cur = cur.next;
        }
        return head;
    }


    // for test
    public static void main(String[] args) {
        int[] arr = {4, 5, 1, 9};
        ListNode head = generateList(arr);
        printListNode(head);

        head = deleteNode(head, 1);
        printListNode(head);
    }

    // for test
    public static void printListNode(ListNode head) {
        if(head == null) {
            return;
        }
        ListNode cur = head;
        while (cur != null) {
            System.out.print(cur.val + " ");
            cur = cur.next;
        }
        System.out.println();
    }

    // for test
    public static ListNode generateList(int[] arr) {
        if(arr == null || arr.length == 0) {
            return null;
        }
        ListNode head = new ListNode(arr[0]);
        ListNode pre = head;
        ListNode cur = null;
        for (int i = 1; i < arr.length; i++) {
            cur = new ListNode(arr[i]);
            pre.next = cur;
            pre = pre.next;
        }
        return head;
    }

}
